<?php
/**
 * 目录管理
 * @since   2018-01-16
 * @author  zhaoxiang <zhaoxiang051405@gmail.com>
 */

namespace app\backstage\controller;


use app\model\AbnormalRecord as RecordModel;
use app\util\ReturnCode;
use app\util\Tools;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Db;

class AbnormalRecord extends Base {



    public function index(){


        $where = [];
        $page = $this->request->get('page', 1);
        $size = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $postData = $this->request->get();

        if (isset($postData['status'])) {
            $where['a.status'] = $postData['status'];
        }

        if (isset($postData['mobile'])) {
            $where['a.mobile'] = $postData['mobile'];
        }

        if (isset($postData['xrkCode'])) {
            $where['a.xrkCode'] = ['like', "%{$postData['xrkCode']}%"];
        }


        if (isset($postData['realname'])) {
            $where['a.realname'] = ['like', "%{$postData['realname']}%"];
        }

        if (isset($postData['platformID'])) {
            $where['a.platformID'] = $postData['platformID'];
        }

        if (isset($postData['type'])) {
            $where['a.type'] = $postData['type'];
        }

        if(isset($postData['beginTime']) && $postData['beginTime'] && isset($postData['endTime']) && $postData['endTime']){
            $where['a.addtime'] = [
                ['>=', strtotime($postData['beginTime'])],
                ['<=', strtotime($postData['endTime'])],
            ];
        }

        $platformID = $this->userPlatform();
        if ($platformID) {
            $where['a.platformID'] = $platformID;
        }else{
            if(isset($postData['platformID'])  && $postData['platformID']){
                $where['a.platformID'] =  $postData['platformID'];
            }
        }

        $model = new \app\model\AbnormalRecord();
        $list =  $model
            ->alias('a')
            ->with('abConfig')
            ->field('a.*,p.name as platformName')
            ->join('platform p', 'p.id=a.platformID', 'left')
            ->limit(( $page - 1 ) * $size , $size)
            ->order('addTime desc')
            ->where($where)
            ->select();


        $count  =  $model->alias('a')->where($where)->count();
        if ($list){
            $list->append(['statusText']);
        }


        return $this->buildSuccess([
            'count'=>$count,
            'list'=>$list,
        ]);
    }

    /**
     * 新增
     */
    public function add() {
        $postData = $this->request->post();
        if (empty($postData['xrkCode'])) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '葵码编号必须填写');
        }
        if (empty($postData['realname'])) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '真实姓名必须填写');
        }
        if (empty($postData['mobile'])) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '手机号必须填写');
        }
        if (empty($postData['type'])) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '异常原因必须选择');
        }

        $postData['mid'] = $this->userInfo['id'];
        $postData['platformID'] = $this->userPlatform();

        $user = \app\model\User::get(['xrkCode' => $postData['xrkCode']]);
        if(!isset($user['userID']))  return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '用户不存在');

        $type = \app\model\AbnormalConfig::get($postData['type']);
        if(!isset($type['id'])) return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '选择的异常原因不存在或已删除');
        $postData['addTime'] = time();
        $postData['userID'] = $user['userID'];
        Db::startTrans();
        try{
            $res = RecordModel::create($postData);
            if(!$res){
                throw new \Exception('异常提交失败');
            }
            $allot = \app\model\UserAllot::where('userID', $user['userID'])->find();
            if($allot){
                $res = \app\model\UserAllot::where('userID', $user['userID'])->update(['status' => 2, 'updateTime' => time()]);
                if(!$res){
                    throw new \Exception('异常提交更新失败1');
                }
                $res = \app\model\User::where('userID', $user['userID'])->update(['isAllot' => 2, 'updataTime' => time()]);
                if(!$res){
                    throw new \Exception('异常提交更新失败2');
                }
            }
            Db::commit();
            return $this->buildSuccess([]);
        }catch (\Exception $e){
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, $e->getMessage());
        }
    }


    /**
     * 状态审批
     */
    public function dataDeal() {
        $id = $this->request->post('abnormalRecordID');
        $status = $this->request->post('status');
        $data = RecordModel::get($id);
        if(!isset($data['abnormalRecordID']))   return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '异常记录不存在');
        if($data['status'] != 1)   return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '异常记录已处理');
        $platformID = $this->userPlatform();
        if($platformID && $data['platformID'] != $platformID){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '不能跨平台处理异常');
        }
        Db::startTrans();
        try{
            $res = RecordModel::update([
                'abnormalRecordID'   => $id,
                'status' => $status
            ]);
            if(!$res){
                throw new \Exception('异常审核失败');
            }
            $this->recoveryAllot($data['userID']);
            Db::commit();
            return $this->buildSuccess([]);
        }catch (\Exception $e){
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, $e->getMessage());
        }
    }

    public function cancel() {
        $id = $this->request->post('abnormalRecordID');
        $data = RecordModel::get($id);
        if(!isset($data['abnormalRecordID']))   return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '异常记录不存在');
        if($data['status'] != -1)   return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '异常记录异常');
        $platformID = $this->userPlatform();
        if($platformID && $data['platformID'] != $platformID){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '不能跨平台处理异常');
        }
        Db::startTrans();
        try{
            $res = RecordModel::update([
                'abnormalRecordID'   => $id,
                'status' => 9
            ]);
            if(!$res){
                throw new \Exception('异常更新失败');
            }
            $this->recoveryAllot($data['userID']);
            Db::commit();
            return $this->buildSuccess([]);
        }catch (\Exception $e){
            Db::rollback();
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, $e->getMessage());
        }
    }


    protected function recoveryAllot($userID){
        $record = RecordModel::where('userID', $userID)->where('status', 'in', [-1, 1, 3])->find();
        if(!empty($record)){
            $res = \app\model\UserAllot::where('userID', $userID)->update(['status' => 1, 'updateTime' => time()]);
            if(!$res){
                throw new \Exception('异常提交失败1');
            }
            $res = \app\model\User::where('userID', $userID)->update(['isAllot' => 1, 'updataTime' => time()]);
            if(!$res){
                throw new \Exception('异常提交失败1');
            }
        }
    }



    public function listDownload(){
        $postData = $this->request->get();
        $where = [];
        if(!isset($postData['acces_token']) || $postData['acces_token'] != 's4fnds5pms86rttb'){
            die('forbidden');
        }
        if (isset($postData['status'])) {
            $where['a.status'] = $postData['status'];
        }

        if (isset($postData['mobile'])) {
            $where['a.mobile'] = $postData['mobile'];
        }

        if (isset($postData['xrkCode'])) {
            $where['a.xrkCode'] = $postData['xrkCode'];
        }

        if (isset($postData['platformID'])) {
            $where['a.platformID'] = $postData['platformID'];
        }

        if (isset($postData['realname'])) {
            $where['a.realname'] = ['like', "%{$postData['realname']}%"];
        }

        if(isset($postData['beginTime']) && $postData['beginTime'] && isset($postData['endTime']) && $postData['endTime']){
            $where['a.addtime'] = [
                ['>=', strtotime($postData['beginTime'])],
                ['<=', strtotime($postData['endTime'])],
            ];
        }
        $platformID = $this->userPlatform();
        if ($platformID) {
            $where['a.platformID'] = $platformID;
        }

        $model = new \app\model\AbnormalRecord();

        $list =  $model
        ->alias('a')
        ->with('abConfig')
        ->field('a.*,p.name as platformName')
        ->join('platform p', 'p.id=a.platformID', 'left')
        ->order('addTime desc')
        ->where($where)
        ->select();

        if($list){
            $list->append(['statusText']);
        }

        $spreadsheet = new Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();

        //表头
        //设置单元格内容
        $worksheet->setCellValueByColumnAndRow(1, 1, '葵码编号');
        $worksheet->setCellValueByColumnAndRow(2, 1, '姓名');
        $worksheet->setCellValueByColumnAndRow(3, 1, '手机号');
        $worksheet->setCellValueByColumnAndRow(4, 1, '异常原因');
        $worksheet->setCellValueByColumnAndRow(5, 1, '备注');
        $worksheet->setCellValueByColumnAndRow(6, 1, '添加时间');
        $worksheet->setCellValueByColumnAndRow(7, 1, '平台');

        $spreadsheet->getActiveSheet()->getDefaultColumnDimension()->setWidth(6);
        $spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(12);
        $spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(25);
        $spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(15);
        $spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(25);
        $spreadsheet->getActiveSheet()->getColumnDimension('E')->setWidth(40);
        $spreadsheet->getActiveSheet()->getColumnDimension('F')->setWidth(12);
        $spreadsheet->getActiveSheet()->getColumnDimension('G')->setWidth(25);

        $styleArray = [
            'font' => [
                'bold' => true
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $worksheet->getStyle('A1:G1')->applyFromArray($styleArray)->getFont()->setSize(12); //头部样式设置
        $len = count($list);
        $j = 0;
        for ($i = 0; $i < $len; $i++) {
            $j = $i + 2; //从表格第3行开始
            $worksheet->setCellValueByColumnAndRow(1, $j, $list[$i]['xrkCode']);
            $worksheet->setCellValueByColumnAndRow(2, $j, $list[$i]['realname']);
            $worksheet->setCellValueByColumnAndRow(3, $j, $list[$i]['mobile']);
            $worksheet->setCellValueByColumnAndRow(4, $j, $list[$i]['ab_config']['name']);
            $worksheet->setCellValueByColumnAndRow(5, $j, $list[$i]['content']);
            $worksheet->setCellValueByColumnAndRow(6, $j, $list[$i]['addTime']);
            $worksheet->setCellValueByColumnAndRow(7, $j, $list[$i]['platformName']);
        }
        if (!empty($postData['beginTime']) && $postData['beginTime'] && !empty($postData['endTime']) && $postData['endTime']) {
            $date = $postData['beginTime'] . " 至 " . $postData['endTime'] . ' 23:59:59';
            $worksheet->setCellValueByColumnAndRow(2, $j + 1, $date);
        }

        $styleArrayBody = [
            'borders' => [
                'allBorders' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
                    'color' => ['argb' => '666666'],
                ],
            ],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
            ],
        ];
        $total_rows = $len + 2;
        //添加所有边框/居中
        $worksheet->getStyle('A1:G' . $total_rows)->applyFromArray($styleArrayBody);

        $filename = '订单列表.xlsx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');

        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $writer->save('php://output');

    }


    public function edit() {
        $data = $this->request->post();
        $id = $this->request->post('abnormalRecordID');
        if(!isset($data['content'])) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '备注参数为空');
        }
        if(!isset($data['status'])) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '状态值必须选择');
        }
        if(!in_array($data['status'], [-1, 1,2,3,9])) return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '状态值异常');
        if(!isset($data['abnormalRecordID']))   return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '异常记录不存在');
        $rdata = RecordModel::get($id);
        $platformID = $this->userPlatform();
        if($platformID && $rdata['platformID'] != $platformID){
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '不能跨平台处理异常');
        }
        $res = Db::name('abnormal_record')->where('abnormalRecordID', $id)
            ->update(['content' => $data['content'], 'status' => $data['status']]);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }




}
